package user

import (
	"dustbe/database"
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func SignIn(c *gin.Context) {
	// 先检查 session
	session := sessions.Default(c)
	user := session.Get("user")
	if user != nil {
		dustUser, err := database.FindUserByName(user.(string))
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "获取用户数据失败"})
			return
		}
		dustUser.HashedPassword = ""
		c.JSON(http.StatusOK, gin.H{"code": 200, "data": dustUser })
		return
	}

	// 不存在则继续使用用户名+密码
	name := c.Query("name")
	password := c.Query("password")

	dustUser, err := database.SignIn(name, password)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}

	// 成功之前保存至session中
	session.Set("user", name)
	err = session.Save()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "保存用户信息失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": dustUser})
}
